﻿Imports IICBusinessLogic.PeriodProcessing
Imports CrystalReportViewer
Imports System.ComponentModel
Imports org.codegen.common.ProgressIndicator
Imports System.Security.Principal

''' <summary>
''' UI related function to Processes a period
''' </summary>
''' <remarks></remarks>
Public Class UIReversePeriod

    Private progress As BackroundProgressIndicator.BackroundProgressIndicator

    Private Property period As Period
    Private Property currentUser As IPrincipal

    Private Property periodProcessor As PeriodProcessReverser
    Private Property backgroundWorker As BackgroundWorker

    Public Sub processReversePeriod(ByVal period As Period)

        'ask user to confirm
        If winUtils.MsgboxQuestion( _
         "Are you sure you want to cancel processing of period" & _
                    period.PeriodDescription & "? All Diplomas and Certificates earnedin this period will be deleted.") _
           <> MsgBoxResult.Yes Then Exit Sub

        Me.currentUser = ModelContext.Current.CurrentUser
        Me.period = period
        Me.progress = New BackroundProgressIndicator.BackroundProgressIndicator
        Me.progress.progressWindowTitle = "Reversing Period(s)"
        Me.progress.showCancel = True
        Me.progress.Start(AddressOf progressReversePeriod)


    End Sub

    Private Sub progressReversePeriod(ByVal sender As Object, ByVal e As DoWorkEventArgs)

        Me.backgroundWorker = CType(sender, BackgroundWorker)
        ModelContext.newCurrent(Me.currentUser)
        Me.periodProcessor = New PeriodProcessReverser(Me.period)

        AddHandler Me.periodProcessor.processGoing, AddressOf processPeriodProgress
        AddHandler Me.periodProcessor.processFinished, AddressOf processPeriodFinished

        Me.periodProcessor.reversePeriodProcess()

    End Sub

    Private Sub processPeriodProgress(ByVal sender As Object, _
                        ByVal e As ProgressableEventArgs)


        backgroundWorker.ReportProgress( _
               CInt((e.currentStep / e.totalSteps) * 100), _
               e.progressMessage)

        If backgroundWorker.CancellationPending Then
            e.wasCancelled = True
            backgroundWorker.CancelAsync()

        End If

    End Sub

    Private Sub processPeriodFinished(ByVal sender As Object, _
                                      ByVal e As ProgressableEventArgs)

        Call Me.progress.EndProcess()
        Call winUtils.MsgboxInfo( _
                   String.Format("Period #{0} Processing was cancelled." & _
                    "You may process this period again for diplomas at any time.", _
                    Me.period.PeriodDescription))


    End Sub

End Class